const api = require('../../utils/api.js');
const { getUserIdFromToken } = require('../../utils/base64.js');

Page({
  data: {
    exampleId: null,
    example: null,
    chatList: [],
    total: 0,
    current: 1,
    size: 20,
    loading: false,
    hasMore: true,
    
    // 用户信息
    userInfo: {},
    
    // 图标URLs
    threeIconUrl: '',
    
    // 评论输入
    commentText: '',
    showCommentModal: false,
    sending: false,
    
    // 作品点赞
    exampleLiked: false,
    exampleLikeCount: 0,
    
    // 聊天互动
    likingIds: [], // 正在点赞的记录ID列表
    
    // 图片预览
    showImagePreview: false,
    previewImageUrl: '',
    saving: false,
    
    // 作品管理
    isOwner: false, // 是否是作品所有者
    showActionMenu: false, // 显示操作菜单
    deleting: false // 删除中状态
  },

  onLoad(options) {
    // 初始化图标URLs
    const { getIconUrl } = require('../../utils/imageUtils.js');
    this.setData({
      threeIconUrl: getIconUrl('three.png')
    });
    
    const exampleId = options.id;
    if (!exampleId) {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      });
      wx.navigateBack();
      return;
    }
    
    this.setData({ exampleId: exampleId });
    
    // 检查登录状态
    this.checkLoginStatus();
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showModal({
        title: '需要登录',
        content: '请先登录后查看作品详情',
        confirmText: '去登录',
        cancelText: '返回',
        success: (res) => {
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/login/login'
            });
          } else {
            wx.navigateBack();
          }
        }
      });
      return;
    }
    
    // 获取用户信息
    this.getUserInfo();
    
    // 加载作品详情
    this.loadExampleDetail();
  },

  /**
   * 获取用户信息
   */
  getUserInfo() {
    try {
      const userInfo = wx.getStorageSync('userInfo');
      if (userInfo) {
        // 如果已经是对象，直接使用；如果是字符串，则解析
        const parsedUserInfo = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo;
        this.setData({ userInfo: parsedUserInfo });
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 设置默认用户信息
      this.setData({ 
        userInfo: {
          nickName: '匿名用户',
          avatarUrl: ''
        }
      });
    }
  },

  /**
   * 获取当前用户ID
   */
  getCurrentUserId() {
    try {
      // 先尝试从用户信息中获取
      const userInfo = wx.getStorageSync('userInfo');
      
      if (userInfo) {
        const parsedUserInfo = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo;
        
        // 后端返回的用户信息中用户ID字段是id
        const userId = parsedUserInfo.id || parsedUserInfo.userId;
        if (userId) {
          return userId;
        }
      }
      
      // 如果用户信息中没有ID，尝试从token中解析
      const token = wx.getStorageSync('token');
      if (token) {
        console.log('尝试从token解析用户ID, token长度:', token.length);
        
        
        try {
          const userIdFromToken = getUserIdFromToken(token);
          if (userIdFromToken) {
            console.log('从token获取用户ID:', userIdFromToken);
            return userIdFromToken;
          }
        } catch (tokenError) {
          console.error('从token解析用户ID失败:', tokenError);
          // 继续尝试其他方法
        }
      }
      
      // 如果都失败了，尝试使用默认值或提示用户重新登录
      console.warn('无法获取用户ID，返回默认值1');
      return 1; // 临时返回默认用户ID，避免功能完全无法使用
    } catch (error) {
      console.error('获取用户ID失败:', error);
      return null;
    }
  },

  /**
   * 加载作品详情
   */
  async loadExampleDetail() {
    if (this.data.loading) return;
    
    try {
      this.setData({ loading: true });
      
      const response = await api.get(`/api/user-works/${this.data.exampleId}/detail`, {
        page: this.data.current,
        size: this.data.size
      });
      
      if (response.success) {
        const { example, chatList, total } = response.data;
        
        // 检查是否是作品所有者
        const currentUserId = this.getCurrentUserId();
        
        // 使用多种方式比较用户ID，确保匹配准确
        let isOwner = false;
        
        if (currentUserId && example.userId) {
          // 方式1：直接比较
          isOwner = currentUserId == example.userId;
          
          // 方式2：转字符串比较
          if (!isOwner) {
            isOwner = String(currentUserId) === String(example.userId);
          }
          
          // 方式3：转数字比较（如果是数字类型）
          if (!isOwner && !isNaN(currentUserId) && !isNaN(example.userId)) {
            isOwner = Number(currentUserId) === Number(example.userId);
          }
        }
        
        // 获取点赞状态
        let likeInfo = { liked: false, likeCount: example.likeCount || 0 };
        try {
          const likeResponse = await api.get(`/api/user-works/${this.data.exampleId}/like-info`);
          if (likeResponse.success) {
            likeInfo = likeResponse.data;
          }
        } catch (error) {
          console.log('获取点赞信息失败，使用默认值:', error);
        }

        // 处理图片URL，确保包含完整的服务器地址
        const config = require('../../utils/config.js');
        if (example.imageUrl && !example.imageUrl.startsWith('http')) {
          example.imageUrl = config.API_BASE_URL + example.imageUrl;
        }

        this.setData({
          example: example,
          chatList: this.data.current === 1 ? chatList : [...this.data.chatList, ...chatList],
          total: total,
          hasMore: chatList.length === this.data.size,
          exampleLiked: likeInfo.liked,
          exampleLikeCount: likeInfo.likeCount,
          isOwner: isOwner,
          loading: false
        });
      } else {
        throw new Error(response.message || '加载失败');
      }
    } catch (error) {
      console.error('加载作品详情失败:', error);
      this.setData({ loading: false });
      
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  /**
   * 预览图片
   */
  previewImage(e) {
    const { url } = e.currentTarget.dataset;
    const imageUrl = url || this.data.example.imageUrl;
    
    // 检查图片URL是否有效
    if (imageUrl && imageUrl !== 'INVALID_URL' && imageUrl !== '') {
      this.setData({
        showImagePreview: true,
        previewImageUrl: imageUrl
      });
    } else {
      wx.showToast({
        title: '图片暂不可用',
        icon: 'none'
      });
    }
  },

  /**
   * 图片加载错误处理
   */
  onImageError(e) {
    console.error('图片加载失败:', e);
    const { url } = e.currentTarget.dataset;
    console.error('失败的图片URL:', url);
    
    wx.showToast({
      title: '图片加载失败，请检查网络',
      icon: 'none',
      duration: 2000
    });
    
    // 尝试重新加载（添加时间戳防止缓存）
    if (url && !url.includes('?t=')) {
      setTimeout(() => {
        const newUrl = url + '?t=' + Date.now();
        console.log('尝试重新加载图片:', newUrl);
        
        // 更新数据中的图片URL
        if (this.data.example && this.data.example.imageUrl === url) {
          this.setData({
            'example.imageUrl': newUrl
          });
        }
      }, 1000);
    }
  },

  /**
   * 关闭图片预览
   */
  closeImagePreview() {
    this.setData({
      showImagePreview: false,
      previewImageUrl: ''
    });
  },

  /**
   * 保存图片到相册
   */
  async saveImageToAlbum() {
    if (this.data.saving) return;
    
    const imageUrl = this.data.previewImageUrl;
    if (!imageUrl || imageUrl === 'INVALID_URL' || imageUrl === '') {
      wx.showToast({
        title: '图片暂不可用，无法保存',
        icon: 'none'
      });
      return;
    }

    try {
      this.setData({ saving: true });
      
      // 检查相册权限
      const authResult = await this.checkAlbumAuth();
      if (!authResult) {
        this.setData({ saving: false });
        return;
      }

      wx.showLoading({ title: '保存中...' });

      // 下载图片
      const downloadResult = await new Promise((resolve, reject) => {
        wx.downloadFile({
          url: imageUrl,
          success: resolve,
          fail: reject
        });
      });

      if (downloadResult.statusCode === 200) {
        // 保存到相册
        await new Promise((resolve, reject) => {
          wx.saveImageToPhotosAlbum({
            filePath: downloadResult.tempFilePath,
            success: resolve,
            fail: reject
          });
        });

        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
      } else {
        throw new Error('下载失败');
      }
    } catch (error) {
      console.error('保存图片失败:', error);
      wx.showToast({
        title: error.errMsg || '保存失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
      this.setData({ saving: false });
    }
  },

  /**
   * 检查相册权限
   */
  async checkAlbumAuth() {
    return new Promise((resolve) => {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.writePhotosAlbum'] === false) {
            // 用户之前拒绝了权限，引导用户手动开启
            wx.showModal({
              title: '需要相册权限',
              content: '保存图片需要访问您的相册，请在设置中开启权限',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  wx.openSetting({
                    success: (settingRes) => {
                      resolve(!!settingRes.authSetting['scope.writePhotosAlbum']);
                    },
                    fail: () => resolve(false)
                  });
                } else {
                  resolve(false);
                }
              }
            });
          } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
            // 第一次请求权限
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => resolve(true),
              fail: () => {
                wx.showToast({
                  title: '需要相册权限才能保存',
                  icon: 'none'
                });
                resolve(false);
              }
            });
          } else {
            // 已经有权限
            resolve(true);
          }
        },
        fail: () => resolve(false)
      });
    });
  },

  /**
   * 分享图片
   */
  shareImage() {
    const imageUrl = this.data.previewImageUrl;
    const example = this.data.example;
    
    if (!imageUrl) {
      wx.showToast({
        title: '图片地址无效',
        icon: 'none'
      });
      return;
    }

    // 触发页面的分享功能
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });

    // 或者显示分享选项
    wx.showActionSheet({
      itemList: ['分享给朋友', '分享到朋友圈', '复制链接'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 分享给朋友 - 会触发 onShareAppMessage
          wx.showToast({
            title: '请点击右上角分享',
            icon: 'none'
          });
        } else if (res.tapIndex === 1) {
          // 分享到朋友圈
          wx.showToast({
            title: '请点击右上角分享到朋友圈',
            icon: 'none'
          });
        } else if (res.tapIndex === 2) {
          // 复制链接
          wx.setClipboardData({
            data: imageUrl,
            success: () => {
              wx.showToast({
                title: '链接已复制',
                icon: 'success'
              });
            }
          });
        }
      }
    });
  },

  /**
   * 显示操作菜单
   */
  showActionMenu() {
    this.setData({ showActionMenu: true });
  },

  /**
   * 隐藏操作菜单
   */
  hideActionMenu() {
    this.setData({ showActionMenu: false });
  },

  /**
   * 保存作品到相册（从菜单调用）
   */
  async saveWorkToAlbum() {
    this.hideActionMenu();
    
    const imageUrl = this.data.example?.imageUrl;
    if (!imageUrl || imageUrl === 'INVALID_URL' || imageUrl === '') {
      wx.showToast({
        title: '图片暂不可用，无法保存',
        icon: 'none'
      });
      return;
    }

    // 设置预览图片URL并调用保存方法
    this.setData({ previewImageUrl: imageUrl });
    await this.saveImageToAlbum();
  },

  /**
   * 分享作品（从菜单调用）
   */
  shareWork() {
    this.hideActionMenu();
    
    const example = this.data.example;
    if (!example) return;

    wx.showActionSheet({
      itemList: ['分享给朋友', '分享到朋友圈', '复制链接'],
      success: (res) => {
        if (res.tapIndex === 0) {
          wx.showToast({
            title: '请点击右上角分享',
            icon: 'none'
          });
        } else if (res.tapIndex === 1) {
          wx.showToast({
            title: '请点击右上角分享到朋友圈',
            icon: 'none'
          });
        } else if (res.tapIndex === 2) {
          wx.setClipboardData({
            data: example.imageUrl,
            success: () => {
              wx.showToast({
                title: '链接已复制',
                icon: 'success'
              });
            }
          });
        }
      }
    });
  },

  /**
   * 删除作品
   */
  async deleteWork() {
    if (!this.data.isOwner || this.data.deleting) return;

    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个作品吗？删除后无法恢复。',
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: async (res) => {
        if (res.confirm) {
          await this.performDelete();
        }
      }
    });
  },

  /**
   * 执行删除操作
   */
  async performDelete() {
    try {
      this.setData({ deleting: true });
      this.hideActionMenu();
      
      wx.showLoading({ title: '删除中...' });

      const response = await api.delete(`/api/user-works/${this.data.exampleId}`);
      
      if (response.success) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        throw new Error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除作品失败:', error);
      wx.showToast({
        title: error.message || '删除失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
      this.setData({ deleting: false });
    }
  },

  /**
   * 预览评论图片
   */
  previewCommentImage(e) {
    const { url } = e.currentTarget.dataset;
    if (url) {
      wx.previewImage({
        urls: [url],
        current: url
      });
    }
  },

  /**
   * 显示评论弹窗
   */
  showCommentModal() {
    this.setData({ 
      showCommentModal: true,
      commentText: ''
    });
  },

  /**
   * 隐藏评论弹窗
   */
  hideCommentModal() {
    this.setData({ 
      showCommentModal: false,
      commentText: '',
      sending: false
    });
  },

  /**
   * 评论输入
   */
  onCommentInput(e) {
    this.setData({
      commentText: e.detail.value
    });
  },

  /**
   * 发送评论
   */
  async sendComment() {
    if (!this.data.commentText.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    if (this.data.sending) return;

    try {
      this.setData({ sending: true });

      const response = await api.post(`/api/user-works/${this.data.exampleId}/chat`, {
        imageUrl: 'comment-only',
        prompt: this.data.commentText.trim(),
        style: this.data.example?.style || '通用',
        size: this.data.example?.size || '1024x1024'
      });

      if (response.success) {
        wx.showToast({
          title: '评论成功',
          icon: 'success'
        });

        this.hideCommentModal();
        
        // 重新加载评论列表
        this.setData({
          current: 1,
          chatList: []
        });
        this.loadExampleDetail();

      } else {
        throw new Error(response.message || '评论失败');
      }
    } catch (error) {
      console.error('发送评论失败:', error);
      wx.showToast({
        title: error.message || '评论失败',
        icon: 'none'
      });
    } finally {
      this.setData({ sending: false });
    }
  },

  /**
   * 切换作品点赞
   */
  async toggleExampleLike() {
    try {
      const response = await api.post(`/api/user-works/${this.data.exampleId}/like`);
      
      if (response.success) {
        const likeInfo = response.data;
        const liked = likeInfo.liked;
        const likeCount = likeInfo.likeCount;
        
        this.setData({
          exampleLiked: liked,
          exampleLikeCount: likeCount
        });
        
        // 如果是点赞操作，自动添加到收藏
        if (liked) {
          await this.addToFavorites(this.data.exampleId);
          wx.showToast({
            title: '已点赞并收藏',
            icon: 'none',
            duration: 1500
          });
        } else {
          // 如果是取消点赞，从收藏中移除
          await this.removeFromFavorites(this.data.exampleId);
          wx.showToast({
            title: '取消点赞',
            icon: 'none',
            duration: 1000
          });
        }
      }
    } catch (error) {
      console.error('点赞失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  /**
   * 切换评论点赞
   */
  async toggleCommentLike(e) {
    const { id, index } = e.currentTarget.dataset;
    const chatId = parseInt(id);
    const idx = parseInt(index);
    
    if (this.data.likingIds.includes(chatId)) return;
    
    try {
      this.setData({
        likingIds: [...this.data.likingIds, chatId]
      });
      
      const response = await api.post(`/api/user-works/chat/${chatId}/like`);
      
      if (response.success) {
        const liked = response.data;
        const chatList = [...this.data.chatList];
        const item = chatList[idx];
        
        if (item) {
          item.liked = liked;
          item.likeCount = (item.likeCount || 0) + (liked ? 1 : -1);
          item.likeCount = Math.max(0, item.likeCount);
        }
        
        this.setData({ chatList });
      }
    } catch (error) {
      console.error('评论点赞失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    } finally {
      this.setData({
        likingIds: this.data.likingIds.filter(id => id !== chatId)
      });
    }
  },

  /**
   * 做同款 - 跳转到AI生成页面
   */
  generateImage() {
    if (!this.data.example) return;
    
    const { title, prompt, style, size } = this.data.example;
    const params = new URLSearchParams({
      prompt: prompt || '',
      style: style || '',
      size: size || '1024x1024'
    });
    
    wx.navigateTo({
      url: `/pages/ai-generate/ai-generate?${params.toString()}`
    });
  },

  /**
   * 添加到收藏
   */
  async addToFavorites(exampleId) {
    try {
      const example = this.data.example;
      const contentData = JSON.stringify({
        prompt: example.prompt,
        style: example.style,
        size: example.size
      });

      await api.addFavorite(
        'user_work',
        exampleId.toString(),
        example.title,
        example.prompt,
        example.imageUrl,
        contentData
      );
    } catch (error) {
      console.error('添加收藏失败:', error);
    }
  },

  /**
   * 从收藏移除
   */
  async removeFromFavorites(exampleId) {
    try {
      await api.removeFavoriteByContent('user_work', exampleId.toString());
    } catch (error) {
      console.error('移除收藏失败:', error);
    }
  },

  /**
   * 上拉加载更多评论
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        current: this.data.current + 1
      });
      this.loadExampleDetail();
    }
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.setData({
      current: 1,
      chatList: [],
      hasMore: true
    });
    this.loadExampleDetail().finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 分享
   */
  onShareAppMessage() {
    if (!this.data.example) {
      return {
        title: 'AI伙伴 - 精美作品',
        path: '/pages/ai-image/ai-image'
      };
    }
    
    return {
      title: `${this.data.example.title} - AI伙伴作品`,
      path: `/pages/user-work-detail/user-work-detail?id=${this.data.example.id}`,
      imageUrl: this.data.example.imageUrl
    };
  }
});